﻿<template>
  <el-dialog :title="isEditMode ? '编辑题目' : '新增题目'" v-model="dialogVisible" width="750px" @closed="handleDialogClosed" destroy-on-close :close-on-click-modal="false">
    <div class="form-container">
      <!-- 步骤指示器 -->
      <div class="steps-container">
        <el-steps :active="activeStep" finish-status="success" simple>
          <el-step title="基本信息" />
          <el-step title="示例数据" />
          <el-step title="高级设置" />
        </el-steps>
      </div>

      <!-- 第一步：基本信息 -->
      <div v-if="activeStep === 1" class="form-section">
        <div class="form-row">
          <div class="form-item">
            <label class="form-label required">题目标题</label>
            <el-input v-model="form.title" placeholder="请输入题目标题" :class="{ 'is-error': attempted && formErrors.title }" maxlength="100" show-word-limit />
            <div v-if="attempted && formErrors.title" class="error-message">请输入题目标题</div>
          </div>

          <div class="form-item">
            <label class="form-label">难度等级</label>
            <el-select v-model="form.difficulty" placeholder="请选择难度" class="full-width">
              <el-option label="简单" value="简单" />
              <el-option label="中等" value="中等" />
              <el-option label="困难" value="困难" />
            </el-select>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">题目分类</label>
          <el-input v-model="form.category" placeholder="请输入题目分类，如：算法、数据结构等" maxlength="50" />
        </div>

        <div class="form-item">
          <label class="form-label required">题目描述</label>
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="6"
            placeholder="请详细描述题目要求、背景信息等"
            :class="{ 'is-error': attempted && formErrors.description }"
            maxlength="2000"
            show-word-limit
          />
          <div v-if="attempted && formErrors.description" class="error-message">请输入题目描述</div>
        </div>
      </div>

      <!-- 第二步：格式说明与示例 -->
      <div v-if="activeStep === 2" class="form-section">
        <div class="form-row">
          <div class="form-item">
            <label class="form-label">输入格式说明</label>
            <el-input v-model="form.inputDescription" type="textarea" :rows="3" placeholder="请描述输入数据的格式要求" maxlength="500" show-word-limit />
          </div>

          <div class="form-item">
            <label class="form-label">输出格式说明</label>
            <el-input v-model="form.outputDescription" type="textarea" :rows="3" placeholder="请描述输出数据的格式要求" maxlength="500" show-word-limit />
          </div>
        </div>

        <div class="example-section">
          <div class="example-title">示例数据</div>
          <div class="form-row">
            <div class="form-item">
              <label class="form-label required">示例输入</label>
              <el-input
                v-model="form.sampleInput"
                type="textarea"
                :rows="4"
                placeholder="请输入示例输入数据"
                :class="{ 'is-error': attempted && formErrors.sampleInput }"
                maxlength="1000"
                show-word-limit
              />
              <div v-if="attempted && formErrors.sampleInput" class="error-message">请输入示例输入数据</div>
            </div>

            <div class="form-item">
              <label class="form-label required">示例输出</label>
              <el-input
                v-model="form.sampleOutput"
                type="textarea"
                :rows="4"
                placeholder="请输入示例输出数据"
                :class="{ 'is-error': attempted && formErrors.sampleOutput }"
                maxlength="1000"
                show-word-limit
              />
              <div v-if="attempted && formErrors.sampleOutput" class="error-message">请输入示例输出数据</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第三步：高级设置 -->
      <div v-if="activeStep === 3" class="form-section">
        <div class="form-row">
          <div class="form-item">
            <label class="form-label">时间限制 (ms)</label>
            <el-input-number v-model="form.timeLimit" :min="100" :max="10000" :step="100" class="full-width" />
          </div>

          <div class="form-item">
            <label class="form-label">内存限制 (MB)</label>
            <el-input-number v-model="form.memoryLimit" :min="16" :max="512" :step="16" class="full-width" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">总分</label>
            <el-input-number v-model="form.totalScore" :min="1" :max="1000" :step="10" class="full-width" />
          </div>

          <div class="form-item">
            <label class="form-label">发布状态</label>
            <el-select v-model="form.status" placeholder="请选择状态" class="full-width">
              <el-option label="草稿" value="草稿" />
              <el-option label="已发布" value="已发布" />
              <el-option label="已下线" value="已下线" />
            </el-select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">是否公开</label>
            <div class="switch-wrapper">
              <el-switch v-model="form.isPublic" active-text="公开" inactive-text="私有" />
            </div>
          </div>
          <div class="form-item"></div>
        </div>

        <div class="form-item">
          <label class="form-label">提示信息</label>
          <el-input v-model="form.hint" type="textarea" :rows="3" placeholder="可以为解题者提供一些提示信息（可选）" maxlength="500" show-word-limit />
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="activeStep > 1" @click="prevStep" :disabled="loading">上一步</el-button>
        <el-button v-if="activeStep < 3" type="primary" @click="nextStep" :disabled="loading">下一步</el-button>
        <el-button v-if="activeStep === 3" type="primary" @click="submitForm" :loading="loading">
          {{ isEditMode ? "更新题目" : "创建题目" }}
        </el-button>
        <el-button @click="dialogVisible = false" :disabled="loading">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue"
import { ElMessage } from "element-plus"
import { useProblemsStore } from "@/stores/modules/problem"
import { deepClone } from "@/utils/helpers/object"

// Props 定义
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  problemData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: "add" // 'add' | 'edit'
  }
})

const emit = defineEmits(["update:visible", "success"])

// 计算是否为编辑模式
const isEditMode = computed(() => props.mode === "edit" || !!props.problemData)

// 响应式数据
const loading = ref(false)
const activeStep = ref(1)
const attempted = ref(false)

// 表单错误状态
const formErrors = reactive({
  title: false,
  description: false,
  sampleInput: false,
  sampleOutput: false
})

// 默认表单数据
const defaultForm = {
  title: "",
  description: "",
  difficulty: "中等",
  category: "算法",
  inputDescription: "",
  outputDescription: "",
  sampleInput: "",
  sampleOutput: "",
  hint: "",
  timeLimit: 1000,
  memoryLimit: 256,
  totalScore: 100,
  status: "草稿",
  isPublic: true
}

// 表单数据
const form = reactive(deepClone(defaultForm))

// 对话框可见性
const dialogVisible = ref(false)

// Store
const problemsStore = useProblemsStore()

// 重置表单错误状态
const resetFormErrors = () => {
  formErrors.title = false
  formErrors.description = false
  formErrors.sampleInput = false
  formErrors.sampleOutput = false
}

// 验证第一步
const validateStep1 = () => {
  let isValid = true

  if (!form.title.trim()) {
    formErrors.title = true
    isValid = false
    ElMessage.error("请输入题目标题")
  } else {
    formErrors.title = false
  }

  if (!form.description.trim()) {
    formErrors.description = true
    isValid = false
    ElMessage.error("请输入题目描述")
  } else {
    formErrors.description = false
  }

  return isValid
}

// 验证第二步
const validateStep2 = () => {
  let isValid = true

  if (!form.sampleInput.trim()) {
    formErrors.sampleInput = true
    isValid = false
    ElMessage.error("请输入示例输入数据")
  } else {
    formErrors.sampleInput = false
  }

  if (!form.sampleOutput.trim()) {
    formErrors.sampleOutput = true
    isValid = false
    ElMessage.error("请输入示例输出数据")
  } else {
    formErrors.sampleOutput = false
  }

  return isValid
}

// 验证第三步
const validateStep3 = () => {
  let isValid = true

  // 验证时间限制范围
  if (form.timeLimit < 100 || form.timeLimit > 10000) {
    ElMessage.error("时间限制必须在100-10000ms范围内")
    isValid = false
  }

  // 验证内存限制范围
  if (form.memoryLimit < 16 || form.memoryLimit > 512) {
    ElMessage.error("内存限制必须在16-512MB范围内")
    isValid = false
  }

  // 验证总分范围
  if (form.totalScore < 1 || form.totalScore > 1000) {
    ElMessage.error("总分必须在1-1000分范围内")
    isValid = false
  }

  return isValid
}

// 验证所有步骤
const validateAllSteps = () => {
  return validateStep1() && validateStep2() && validateStep3()
}

// 下一步
const nextStep = () => {
  attempted.value = true

  let isValid = false
  if (activeStep.value === 1) {
    isValid = validateStep1()
  } else if (activeStep.value === 2) {
    isValid = validateStep2()
  }

  if (isValid && activeStep.value < 3) {
    activeStep.value++
  }
}

// 上一步
const prevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value--
  }
}

// 加载题目数据（编辑模式）
const loadProblemData = problemData => {
  if (!problemData) return

  // 重置表单
  Object.assign(form, deepClone(defaultForm))

  // 加载数据
  form.title = problemData.title || ""
  form.description = problemData.description || ""
  form.difficulty = problemData.difficulty || "中等"
  form.category = problemData.category || "算法"
  form.inputDescription = problemData.inputDescription || ""
  form.outputDescription = problemData.outputDescription || ""
  form.sampleInput = problemData.sampleInput || ""
  form.sampleOutput = problemData.sampleOutput || ""
  form.hint = problemData.hint || ""
  form.timeLimit = Number(problemData.timeLimit) || 1000
  form.memoryLimit = Number(problemData.memoryLimit) || 256
  form.totalScore = Number(problemData.totalScore) || 100
  form.status = problemData.status || "草稿"
  form.isPublic = problemData.isPublic !== undefined ? problemData.isPublic : true

  // 重置状态
  resetFormErrors()
  activeStep.value = 1
  attempted.value = false
}

// 格式化表单数据
const formatFormData = () => {
  const formattedData = {
    title: form.title.trim(),
    description: form.description.trim(),
    difficulty: form.difficulty,
    category: form.category.trim() || "算法",
    inputDescription: form.inputDescription.trim(),
    outputDescription: form.outputDescription.trim(),
    sampleInput: form.sampleInput.trim(),
    sampleOutput: form.sampleOutput.trim(),
    hint: form.hint.trim(),
    timeLimit: form.timeLimit,
    memoryLimit: form.memoryLimit,
    totalScore: form.totalScore,
    status: form.status,
    isPublic: form.isPublic
  }

  // 如果是编辑模式，添加ID
  if (isEditMode.value && props.problemData?.id) {
    formattedData.id = props.problemData.id
  }

  return formattedData
}

// 提交表单
const submitForm = async () => {
  attempted.value = true

  if (!validateAllSteps()) {
    ElMessage.error("请完成所有必填字段的填写")
    return
  }

  loading.value = true
  try {
    const formattedData = formatFormData()
    let result

    if (isEditMode.value) {
      result = await problemsStore.updateProblem(formattedData.id, formattedData)
    } else {
      result = await problemsStore.createProblem(formattedData)
    }

    if (result && result.code === 200) {
      ElMessage.success(isEditMode.value ? "题目更新成功" : "题目创建成功")
      dialogVisible.value = false
      emit("success")
    } else {
      ElMessage.error(result?.message || (isEditMode.value ? "更新失败" : "创建失败"))
    }
  } catch (error) {
    ElMessage.error(error.message || "操作失败，请稍后重试")
  } finally {
    loading.value = false
  }
}

// 处理对话框关闭
const handleDialogClosed = () => {
  // 重置表单
  Object.assign(form, deepClone(defaultForm))
  resetFormErrors()
  activeStep.value = 1
  attempted.value = false

  emit("update:visible", false)
}

// 监听props.visible变化
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal

    if (newVal && props.problemData) {
      loadProblemData(props.problemData)
    }
  },
  { immediate: true }
)

// 监听dialogVisible变化
watch(dialogVisible, newVal => {
  if (props.visible !== newVal) {
    emit("update:visible", newVal)
  }
})
</script>

<style lang="scss" scoped>
@use "@/styles/base/variables" as *;

.form-container {
  width: 100%;
}

.steps-container {
  margin-bottom: $spacing-md;
  padding: $spacing-base;
  background: linear-gradient(135deg, $color-primary-light-9, $bg-color-white);
  border-radius: $border-radius-base;
  border: 1px solid $border-color-lighter;
}

.form-section {
  min-height: 280px;
}

.form-row {
  display: flex;
  align-items: flex-start;
  gap: $spacing-md;
  margin-bottom: $spacing-base;

  &:last-child {
    margin-bottom: 0;
  }

  @media (max-width: 768px) {
    flex-direction: column;
    gap: $spacing-xs;
  }
}

.form-item {
  flex: 1;
  margin-bottom: $spacing-base;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: $font-size-sm;
  font-weight: $font-weight-medium;
  color: $color-text-secondary;
  margin-bottom: 6px;
  height: 20px;
  line-height: 20px;

  &.required::after {
    content: " *";
    color: $color-danger;
  }
}

.error-message {
  color: $color-danger;
  font-size: $font-size-xs;
  margin-top: 4px;
}

.full-width {
  width: 100%;
}

.switch-wrapper {
  height: 32px;
  display: flex;
  align-items: center;
}

.example-section {
  background: $bg-color-layout;
  border: 1px dashed $border-color-light;
  border-radius: $border-radius-base;
  padding: $spacing-base;
  margin-top: $spacing-base;

  .example-title {
    font-size: $font-size-base;
    font-weight: $font-weight-medium;
    color: $color-text-primary;
    margin-bottom: $spacing-base;
    text-align: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: $spacing-sm;

  .el-button {
    min-width: 80px;
  }
}

// Element Plus 样式覆盖
:deep(.el-dialog) {
  border-radius: $border-radius-lg;
  box-shadow: $box-shadow-lg;
}

:deep(.el-dialog__header) {
  padding: $spacing-md $spacing-lg;
  border-bottom: 1px solid $border-color-lighter;
}

:deep(.el-dialog__title) {
  font-size: $font-size-lg;
  font-weight: $font-weight-semibold;
  color: $color-text-primary;
}

:deep(.el-dialog__body) {
  padding: $spacing-md $spacing-lg;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  padding: $spacing-base $spacing-lg;
  border-top: 1px solid $border-color-lighter;
}

:deep(.el-input) {
  .el-input__wrapper {
    min-height: 32px;
  }

  &.is-error .el-input__wrapper {
    box-shadow: 0 0 0 1px $color-danger inset;
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    min-height: 32px;
  }
}

:deep(.el-input-number) {
  .el-input__wrapper {
    min-height: 32px;
  }
}

:deep(.el-textarea.is-error .el-textarea__inner) {
  box-shadow: 0 0 0 1px $color-danger inset;
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: $spacing-sm;
  }

  .form-row {
    gap: $spacing-xs;
  }

  .dialog-footer {
    flex-direction: column;
    gap: $spacing-xs;

    .el-button {
      width: 100%;
    }
  }
}
</style>
